package controllers

import (
	"github.com/astaxie/beego"
	"shop/common"
	"shop/models"
	"time"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Login() {
	username := c.GetString("username")
	password := c.GetString("password")
	key := "lock-" + username
	count, _ := models.Rdb.Get(key).Int()
	if count >= 3 {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "账号密码错误,两小时后重试",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	var user models.User
	err := models.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "用户不存在",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		if password == common.Md5(password) {
			models.Rdb.Get(key)
			c.Data["json"] = JsonRes{
				Code: 200,
				Msg:  "登录成功",
				Data: nil,
			}
			c.ServeJSON()
			return
		} else {
			models.Rdb.Incr(key)
			models.Rdb.Expire(key, time.Hour*2)
			c.Data["json"] = JsonRes{
				Code: 500,
				Msg:  "密码错误",
				Data: nil,
			}
			c.ServeJSON()
		}
	}

}
